package com.example.mvt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Lockport extends ListActivity {
	ArrayList<String> names = new ArrayList<String>();
	ArrayList<String> phones = new ArrayList<String>();
	ArrayList<String> pics = new ArrayList<String>();
	final Context context = this;
	
	String username;
	
	ArrayList<Employee> empslist = new ArrayList<Employee>();
	Bitmap emppic = null;
	private static final String PHP_GET = "http://webdev.cs.uwosh.edu/students/meyers11/PHPLock.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lockport);
		new GetListTask().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.lockport, menu);
		return true;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onListItemClick(ListView list, View view, int position, long id) {
		super.onListItemClick(list, view, position, id);
		
		HashMap<String, String> hm = new HashMap<String,String>();
		
		hm = (HashMap<String, String>) list.getAdapter().getItem(position);
		
		String name = hm.get("nm");

		for(Employee e : empslist){
			if(e.getName().equals(name)){
				AlertDialog.Builder alert = new AlertDialog.Builder(this);   
				
				LinearLayout lila1= new LinearLayout(this);
			    lila1.setOrientation(1); 
			    final TextView name2 = new TextView(this); 
			    name2.setText(name);
			    final TextView phone = new TextView(this);
			    phone.setText("Phone: " + e.getPhone());
			    TextView position2 = new TextView(this);
			    position2.setText(e.getPosition());
			    alert.setTitle(name);  
			    name2.setTextSize(22);
			    phone.setTextSize(22);
			    name2.setPadding(15,0,0,0);
			    phone.setPadding(15,0,0,0);
			    position2.setPadding(15,0,0,0);
			    position2.setTextSize(20);
			    //lila1.addView(name2);
			    lila1.addView(position2);	 
			    lila1.addView(phone);
			    alert.setView(lila1);

				alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
				  public void onClick(DialogInterface dialog, int whichButton) {
				    // Close.
				  }
				});

				alert.show();
			}
		}
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		new GetListTask().execute();
		new getLoginInfo().execute();
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {	
	        case R.id.action_logout:
	        	new Logout().execute();
	        	Intent myIntent3 = new Intent(Lockport.this, LoginActivity.class);
				startActivityForResult(myIntent3, 0);
				Lockport.this.finish();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	//Logout
	private class Logout extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MVTDataSource mds2 = new MVTDataSource(Lockport.this);
			
			mds2.open();
			
			try {
				mds2.logoutUser();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mds2.close();
			
			return "";
		}
		
		@Override
		protected void onPostExecute(String whatever) {
				Intent myIntent = new Intent(Lockport.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				Lockport.this.finish();
		}
		
	}
	
	//Get Login Info
	private class getLoginInfo extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MVTDataSource mds2 = new MVTDataSource(Lockport.this);
			
			mds2.open();
			
			try {
				username = mds2.getUsername();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mds2.close();
			
			return username;
		}
		
		@Override
		protected void onPostExecute(String whatever) {
			if (username.equals("user")){
				Intent myIntent = new Intent(Lockport.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				return;
			}
			else{
				return;
			}
		}
		
	}
	
	public class GetListTask extends AsyncTask<Void, Void, ArrayList<Employee>> {
		@Override
		protected ArrayList<Employee> doInBackground(Void... params) {
			
			System.out.println("HELLO");
			
			ArrayList<Employee> emps = new ArrayList<Employee>();
			// TODO: attempt authentication against a network service.
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_GET);
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);
					System.out.println("HELLOOO" + response);

					//Parse JSON Data
					int id;
					String position = "";
					String name = "";
					String phone = "";

					try{

						JSONArray jArray = new JSONArray(response);
						
						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);
							
							position = json_data.getString("position");
							id = Integer.parseInt(json_data.getString("id"));
							name = json_data.getString("name");
							phone = json_data.getString("phone");
							
							Employee e = new Employee(id,name,phone,position,"default");
							emps.add(e);
						}
						
					}catch(JSONException e1){
						e1.printStackTrace();
						System.out.println("HELLO JSON error: " + e1);
					}
				}
				catch(Exception e){
					System.out.println("HELLO connection error: " + e);
					
				}
			}
			
			empslist = emps;
			return emps;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Employee> e) {
            List<HashMap<String,String>> eList = new ArrayList<HashMap<String,String>>();
            
            for(int i=0;i<e.size();i++){
            	HashMap<String, String> hm = new HashMap<String,String>();
                hm.put("nm",e.get(i).getName()); 
                hm.put("pic", Integer.toString(R.drawable.star));
               
                eList.add(hm);
            }
            
            String[] keys = {"nm","pic"};
            
            int[] ids = {R.id.name,R.id.profpic};
            
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), eList, R.layout.listview_layout, keys, ids);
            
           setListAdapter(adapter);

        }

	}
	

}
